var actionURL = '/MJOrder/ashx/MJOrderHandler.ashx';
var formurl = '/MJOrder/html/MJOrder.html';

$(function () {

    //为避免数据字典加载不完整。这段在后面加载
    //autoResize({ dataGrid: '#list', gridType: 'datagrid', callback: grid.bind, height: 0 });

    $('#a_add').click(CRUD.add);
    $('#a_edit').click(CRUD.edit);
    $('#a_delete').click(CRUD.del);
    //高级查询
    $('#a_search').click(function () {
        search.go('list');
    });
    $('#a_refresh').click(grid.reload);//刷新
    $('#a_getSearch').click(function () {//自定义搜索框
        mySearch();
    });

    $('#mysearch').click(function () {
        console.log("自定义搜索");
        var sroomno = $("#searchroomno").textbox("getValue");
        var suser = $("#searchuser").textbox('getValue');
        var smobile = $("#searchmobile").textbox('getValue');
        var sconnman = $("#searchconnman").textbox("getValue");
        var query = '{"groupOp":"AND","rules":[],"groups":[]}';
        var o = JSON.parse(query);
        var i = 0;
        if (sroomno != '' && sroomno != undefined) {//假如房间号不为空
            o.rules[i] = JSON.parse('{"field":"roomno","op":"cn","data":"' + sroomno + '"}');
            i = i + 1;
        }
        if (suser != '' && suser != undefined) {//入住人不为空
            o.rules[i] = JSON.parse('{"field":"usernames","op":"cn","data":"' + suser + '"}');
        }
        if (smobile != '' && smobile != undefined) {//入住人手机号
            o.rules[i] = JSON.parse('{"field":"usermobiles","op":"cn","data":"' + smobile + '"}');
        }//contact
        if (sconnman != '' && sconnman != undefined) {//经办人
            o.rules[i] = JSON.parse('{"field":"contact","op":"cn","data":"' + sconnman + '"}');
        }
        if (sconnman == '' && smobile == '' && suser == '' && sroomno == '') {
            $('#list').datagrid('clearSelections').datagrid('reload', { filter: '' });

        } else {
            $('#list').datagrid('reload', { filter: JSON.stringify(o) });
        }


    });


    /*导出EXCEL*/
    $('#a_export').click(function () {
        var ee = new ExportExcel('list', actionURL);
        ee.go();
    });

    /*导入EXCEL*/
    $('#a_inport').click(function () {
        var ii = new ImportExcel('list', actionURL);
        ii.go();
    });

    //批量删除
    $("#a_alldel").click(function () {
        var ids = [];
        var rows = $('#list').datagrid('getSelections');
        for (var i = 0; i < rows.length; i++) {
            ids.push(rows[i].KeyId);
        }
        var allid = ids.join(',');//所有的id
        var o = {};
        o.action = "alldel";
        o.KeyIds = allid;
        var param = "json=" + JSON.stringify(o);

        if (confirm('确认要执行批量删除操作吗？')) {
            jQuery.ajaxjson(actionURL, param, function (d) {
                if (parseInt(d) > 0) {
                    msg.ok('批量删除成功！');
                    grid.reload();
                } else {
                    MessageOrRedirect(d);
                }
            });
        }


    });



});
//这段后加载，避免数据字典加载不完整的问题
window.onload = function () {
    autoResize({ dataGrid: '#list', gridType: 'datagrid', callback: grid.bind, height: 0 });
};


//editor:'datetimebox' 日期及时间选择框  editor:'datebox' 日期选择框    editor:'numberspinner' 数字调节器  editor:{type: 'numberspinner',options:{value:0,required:true}}

//定义一个$JQ为$.　以后在js 中就可以用${JQ}AJAX了在前台这样写(定义)://通用数据字典start
var getDic = {
    jsonData: function (dicID) {
        $.getJSON('/sys/ashx/dichandler.ashx?categoryId=' + dicID + '', function (data) {
            var newData = JSON.stringify(data).replace(/KeyId/g, "id").replace(/Title/g, "text");
            //alert(newData);
            $('body').data('data' + dicID + '', newData); //意思是得到数据并赋值给body
        });
    },
    jsonParentData: function (dicID) {
        $.getJSON('/sys/ashx/dichandler.ashx?action=parent&parentid=' + dicID + '', function (data) {
            var newData = JSON.stringify(data).replace(/KeyId/g, "id").replace(/Title/g, "text");
            $('body').data('data' + dicID + '', newData); //意思是得到数据并赋值给body
        });
    },
}

//通用数据字典end
//调用数据字典和使用数据字典 如果不需要请不要打开否则会导致系统速度慢
//getDic.jsonData(9);//取得性别数据字典
//在onLoad:的地方如下使用
//top.$('#txt_user_sex').combobox({ data: eval($('body').data('data9')), valueField: 'text', textField: 'text', editable: false, required: true, missingMessage: '请选择性别', disabled: false });





var grid = {
    bind: function (winSize) {
        $('#list').datagrid({
            queryParams: {
                filter: '{"groupOp":"AND","rules":[{"field":"orderstatus","op":"eq","data":"0"}],"groups":[]}',
            },
            url: actionURL,
            toolbar: '#toolbar',
            title: "订单列表",
            iconCls: 'icon icon-list',
            width: winSize.width,
            height: winSize.height,
            nowrap: false, //折行
            rownumbers: true, //行号
            striped: true, //隔行变色
            idField: 'KeyId',//主键
            singleSelect: true, //单选
            frozenColumns: [[]],
            columns: [[//应为宽度不是很需要所以注释了宽度
                { title: '选择', field: 'ck', checkbox: true },//后加进去全选字段数据库里是没有的
                { title: '系统标识', field: 'KeyId', sortable: true, editor: 'numberspinner', width: '', hidden: true },//主键自动判断隐藏
                { title: '合同编号', field: 'edNumber', sortable: true, width: '150', hidden: false },
                {
                    title: '客户姓名', field: 'usernames', sortable: true, width: '',

                    formatter: function (value, row, index) {
                        //return new Date(row.nextpaydate).Format("yyyy-MM-dd");
                        if (row.usernames.indexOf(',') >= 0) {
                            var newstr = "";
                            //return "包含,";
                            str = row.usernames; //这是一字符串 
                            var strs = new Array(); //定义一数组 
                            strs = str.split(","); //字符分割 
                            for (i = 0; i < strs.length; i++) {
                                //document.write(strs[i] + "<br/>"); //分割后的字符输出 
                                newstr = newstr + strs[i] + "<br/>";
                            }

                            return newstr;

                        } else {
                            return row.usernames;//"不包含";
                        }

                    },

                    hidden: false
                },
                { title: '用户ID', field: 'usersid', sortable: true, editor: 'numberspinner', width: '', hidden: true },//主键自动判断隐藏
                { title: '房号', field: 'roomno', sortable: true, width: '', hidden: false },
                { title: '房间ID', field: 'roomid', sortable: true, editor: 'numberspinner', width: '', hidden: true },//主键自动判断隐藏
                {
                    title: '手机号', field: 'usermobiles', sortable: true, width: '',

                    formatter: function (value, row, index) {
                        //return new Date(row.nextpaydate).Format("yyyy-MM-dd");
                        if (row.usermobiles.indexOf(',') >= 0) {
                            var newstr = "";
                            //return "包含,";
                            str = row.usermobiles; //这是一字符串 
                            var strs = new Array(); //定义一数组 
                            strs = str.split(","); //字符分割 
                            for (i = 0; i < strs.length; i++) {
                                //document.write(strs[i] + "<br/>"); //分割后的字符输出 
                                newstr = newstr + strs[i] + "<br/>";
                            }

                            return newstr;

                        } else {
                            return row.usermobiles;//"不包含";
                        }

                    },
                    hidden: false
                },
                { title: '金额合计', field: 'total', sortable: true, width: '', hidden: false },
                { title: '入款账户', field: 'account', sortable: true, width: '', hidden: false },
                {
                    title: '入住时间', field: 'add_time', sortable: true, width: '',
                    formatter: function (value, row, index) {
                        return new Date(row.add_time).Format("yyyy-MM-dd");
                    },

                    hidden: false
                },
                {
                    title: '下次交租', field: 'nextpaydate', sortable: true, width: '',
                    formatter: function (value, row, index) {
                        return new Date(row.nextpaydate).Format("yyyy-MM-dd");
                        //return tab(new Date(row.nextpaydate).Format("yyyy-MM-dd"));
                    },
                    hidden: false
                },
                {
                    title: '状态', field: 'zst', width: '', hidden: false, formatter: function (value, row, index) {
                        if (row.orderstatus == -1) {
                            return '';
                        } else {
                            //下次交租说的是房租
                            return tab(new Date(row.nextpaydate).Format("yyyy-MM-dd"));
                        }


                    }
                },
                { title: '操作', field: 'printsj', width: '', hidden: false, formatter: formatOper },
                { title: '更新时间', field: 'up_time', sortable: true, editor: 'datetimebox', width: '', hidden: true },//主键自动判断隐藏
                { title: '订单状态', field: 'orderstatus', sortable: true, width: '', hidden: true },
            ]],
            onEndEdit: onEndEdit,//结束编辑时函数 这里为了简洁 该函数写在下面
            onUnselect: onUnselect,
            onLoadSuccess: function (data) {
                //alert($('body').data('data70'));
                //alert($('body').data('data69'));
            },
            onCancelEdit: onCancelEdit,//在用户取消编辑一行的时候触发
            onSelect: onSelect,//在用户选择一行的时候触发
            onClickRow: onClickRow,//在用户点击一行的时候触发
            //onAfterEdit: onAfterEdit,//在用户完成编辑一行的时候触发
            onDblClickCell: onDblClickCell,//为了程序逻辑清楚函数写在外面
            onHeaderContextMenu: function (e, field) {//列菜单实现动态隐藏列
                e.preventDefault();
                if (!cmenu) {
                    createColumnMenu();
                }
                cmenu.menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            },
            rowStyler: function (index, row) {
                if (row.orderstatus == -1) {
                    return 'background-color:pink;color:blue;font-weight:bold;';
                }
            },
            view: detailview,
            detailFormatter: function (index, row) {
                return '<div class="ddv" style="padding:5px 0"></div>';
            },
            onExpandRow: function (index, row) {//展开的时候
                $.ajax({
                    type: "POST",
                    //url: "/MJOrderDetail/ashx/MJOrderDetailHandler.ashx?t=list&KeyId=" + row.KeyId + "",
                    url: "/MJOrderDetail/ashx/MJOrderDetailHandler.ashx",
                    //data: { "filter": "{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"financeId\",\"op\":\"eq\",\"data\":\"" + row.KeyId + "\"}],\"groups\":[]}" },
                    data: { "filter": "{\"groupOp\": \"AND\", \"rules\": [{\"field\":\"MJOrderid\",\"op\":\"eq\",\"data\": \"" + row.KeyId + "\" }], \"groups\": [] }" },
                    dataType: "json",
                    beforeSend: function () { },
                    complete: function () { },
                    success: function (d) {
                        //alert(JSON.stringify(d));
                        var temptab = "<table><tbody>";
                        temptab = temptab + "<tr><td colspan=8><center>服&nbsp;&nbsp;务&nbsp;&nbsp;信&nbsp;&nbsp;息</center></td></tr>";
                        temptab = temptab + "<tr><td>序号</td><td>服务名称</td><td>单价</td><td>数量</td><td>总价</td><td>服务开始时间</td><td>服务到期时间</td><td>备注</td></tr>";
                        var temptrtd = "";
                        $.each(d.rows, function (i, item) {

                            temptrtd = temptrtd + "<tr><td>" + (parseInt(i + 1)) + "</td><td>" + item.serviceName + "</td><td>" + item.sprice + "</td><td>" + item.num + "</td><td>" + item.allprice + "</td><td>" + item.add_time + "</td><td>" + item.exp_time + "</td><td>" + item.note + "</td></tr>";
                        });
                        temptab = temptab + temptrtd + "</tbody></table>";

                        console.log("第一个ajax加载完");

                        //加载另外表格
                        $.ajax({
                            type: "POST",
                            //url: "/MJOrderDetail/ashx/MJOrderDetailHandler.ashx?t=list&KeyId=" + row.KeyId + "",
                            url: "/mjfinancemain/ashx/MJFinanceMainHandler.ashx",
                            //data: { "filter": "{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"financeId\",\"op\":\"eq\",\"data\":\"" + row.KeyId + "\"}],\"groups\":[]}" },
                            data: { "filter": "{\"groupOp\": \"AND\", \"rules\": [{\"field\":\"roomno\",\"op\":\"eq\",\"data\": \"" + row.roomno + "\" },{\"field\":\"unit\",\"op\":\"eq\",\"data\": \"" + row.users + "\" }], \"groups\": [] }" },
                            dataType: "json",
                            beforeSend: function () { },
                            complete: function () { },
                            success: function (d) {
                                //表格二
                                temptab = temptab + "<hr/><table><tbody>";
                                temptab = temptab + "<tr><td colspan=6><center>单&nbsp;&nbsp;据&nbsp;&nbsp;信&nbsp;&nbsp;息</center></td><tr/>";
                                temptab = temptab + "<tr><td>序号</td><td>日期</td><td>单号</td><td>类型</td><td>经手人</td><td>操作</td></tr>";
                                $.each(d.rows, function (i, item) {
                                    var sysdate = $("#sysdate").html();//获得服务器时间
                                    console.log("现在服务器时间" + sysdate);
                                    console.log("操作时间" + item.add_time);
                                    var result = GetDateDiff(sysdate, item.add_time, "day");
                                    console.log("时间相差：" + result);
                                    var edit = "";
                                    var edittitle = "修改";
                                    if (result == 0) {

                                    } else {
                                        edit = "disabled='disabled'";//超过一天拒绝修改
                                        edittitle = "超过一天禁止修改";
                                    }

                                    if (row.orderstatus == -1) {//如果是已退房的不允许修改
                                        edit = "disabled='disabled'";//超过一天拒绝修改
                                        edittitle = "已退房禁止修改";
                                    }

                                    var t = item.edNumber;
                                    var xfinput = "";
                                    //alert(t);
                                    var mytype = "财务";
                                    if (t.indexOf("RZ") > -1) {
                                        mytype = "入住";
                                    }
                                    if (t.indexOf("XF") > -1) {
                                        mytype = "续费";
                                        //补打续费收据
                                        xfinput = "<input type='button' onclick=PrintXF('" + t + "') value='补打续费收据'>";
                                    }
                                    if (t.indexOf("TZ") > -1) {
                                        mytype = "退房";
                                        edit = "disabled='disabled'";//超过一天拒绝修改
                                        edittitle = "退房收据不允许修改";
                                        //补打续费收据
                                        xfinput = "<input type='button' onclick=PrintTZ('" + t + "') value='补打退房收据'>";
                                    }
                                    temptab = temptab + "<tr><td>" + (parseInt(i + 1)) + "</td><td>" + item.add_time + "</td><td>" + item.edNumber + "</td><td>" + mytype + "</td><td>" + item.contact + "</td><td><input type='button' " + edit + " onclick=myedit('" + item.edNumber + "','" + row.KeyId + "','" + row.usersid + "','" + row.roomid + "'); value='" + edittitle + "'>" + xfinput + "</td></tr>";
                                });
                                temptab = temptab + "</tbody></talbe>";
                                console.log("第二个ajax加载完");
                                //第二个ajax加载完才显示
                                var ddv = $("#list").datagrid('getRowDetail', index).find('div.ddv');
                                ddv.panel({//把这个div 弄成面板                                 border:false,
                                    content: "" + temptab + "",
                                    onLoad: function () {
                                        //$('#financeDetail').datagrid('fixDetailRowHeight',index); 
                                    }
                                });
                                $('#list').datagrid('fixDetailRowHeight', index);
                                //
                            }
                        });
                        //加载另外表格


                    }
                });
                $('#list').datagrid('fixDetailRowHeight', index);
            },
            pagination: true,
            pageSize: PAGESIZE,
            pageList: [20, 40, 50, 100, 200],

        });
    },
    getSelectedRow: function () {
        return $('#list').datagrid('getSelected');
    },
    reload: function () {
        //alert("加载");
        //$('#list').datagrid('reload', { filter: '{"groupOp":"AND","rules":[{"field":"orderstatus","op":"eq","data":"0"}],"groups":[]}' });
        console.log("表单重载");
        $('#list').datagrid('clearSelections').datagrid('reload', { filter: '{"groupOp":"AND","rules":[{"field":"orderstatus","op":"eq","data":"0"}],"groups":[]}' });
    },

};

function createParam(action, keyid) {
    var o = {};
    var query = top.$('#uiform').serializeArray();
    query = convertArray(query);
    o.jsonEntity = JSON.stringify(query);
    o.action = action;
    o.keyid = keyid;
    return "json=" + JSON.stringify(o);
}


var CRUD = {
    add: function () {
        var hDialog = top.jQuery.hDialog({
            title: '添加', width: 1000, height: 800, href: formurl, iconCls: 'icon-add',
            onLoad: function () {
                top.$('#txt_users').combobox({ url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJUser&field=fullname', valueField: 'fullname', textField: 'fullname', editable: true, required: true, missingMessage: '请输入姓名', disabled: false });
                top.$('#txt_roomno').combobox({ url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJRooms&field=roomnumber', valueField: 'roomnumber', textField: 'roomnumber', editable: true, required: true, missingMessage: '房号不能为空', disabled: false });
                top.$('.kindeditor').kindeditor();//初始化kingdeditor编辑器
            },
            submit: function () {
                //alert(top.$("#uiform").form('enableValidation').form('validate'));
                //alert(top.$("#uiform").form('validate'));
                //原来用的是这种方法 alert(top.$('#uiform').validate().form());
                if (top.$("#uiform").form('validate')) {
                    var query = createParam('add', '0');
                    jQuery.ajaxjson(actionURL, query, function (d) {
                        if (parseInt(d) > 0) {
                            msg.ok('添加成功！');

                            hDialog.dialog('close');
                            grid.reload();
                        } else {
                            MessageOrRedirect(d);
                        }
                    });
                }
                msg.warning('请填写必填项！');
                return false;
            }
        });

        top.$('#uiform').validate();
    },
    edit: function () {
        var row = grid.getSelectedRow();
        if (row) {
            var hDialog = top.jQuery.hDialog({
                title: '编辑', width: 1000, height: 700, href: formurl, iconCls: 'icon-save',
                onLoad: function () {
                    top.$('#txt_KeyId').numberspinner('setValue', row.KeyId);
                    top.$('#txt_users').combobox({ url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJUser&field=fullname', valueField: 'fullname', textField: 'fullname', editable: true, required: true, missingMessage: '请输入姓名', disabled: false });
                    top.$('#txt_users').combobox('setValue', row.users);
                    top.$('#txt_usersid').numberspinner('setValue', row.usersid);
                    top.$('#txt_roomno').combobox({ url: '/sys/ashx/DataSourceFieldHandler.ashx?tablename=MJRooms&field=roomnumber', valueField: 'roomnumber', textField: 'roomnumber', editable: true, required: true, missingMessage: '房号不能为空', disabled: false });
                    top.$('#txt_roomno').combobox('setValue', row.roomno);
                    top.$('#txt_roomid').numberspinner('setValue', row.roomid);
                    top.$('#txt_mobile').textbox('setValue', row.mobile);
                    top.$('#txt_total').textbox('setValue', row.total);
                    top.$('#txt_add_time').datetimebox('setValue', row.add_time);
                    top.$('#txt_up_time').datetimebox('setValue', row.up_time);
                    //top.$('#txt_$item.colAttribute').val(row.$item.colAttribute);//$item.coltitle
                    //top.$('.kindeditor').kindeditor();//初始化kingdeditor编辑器
                    //注意 如果控件被EasyUI初始化过，赋值的方法有所改变 下面提供几个例子。程序员根据情况改动一下
                    //$('#nn').numberbox('setValue', 206.12);
                    //$('#nn').textbox('setValue',1);
                    //$('#cc').combobox('setValues', ['001','002']);
                    //$('#dt').datetimebox('setValue', '6/1/2012 12:30:56');    
                },
                submit: function () {
                    //alert(top.$("#uiform").form('enableValidation').form('validate'));
                    //alert(top.$("#uiform").form('validate'));
                    //原来用的是这种方法 alert(top.$('#uiform').validate().form());
                    if (top.$("#uiform").form('validate')) {
                        var query = createParam('edit', row.KeyId);;
                        jQuery.ajaxjson(actionURL, query, function (d) {
                            if (parseInt(d) > 0) {
                                msg.ok('修改成功！');
                                hDialog.dialog('close');
                                grid.reload();
                            } else {
                                MessageOrRedirect(d);
                            }
                        });
                    }
                    msg.warning('请填写必填项！');
                    return false;
                }
            });

        } else {
            msg.warning('请选择要修改的行。');
        }
    },
    del: function () {
        var row = grid.getSelectedRow();
        if (row) {
            if (confirm('确认要执行删除操作吗？')) {
                var rid = row.KeyId;
                jQuery.ajaxjson(actionURL, createParam('delete', rid), function (d) {
                    if (parseInt(d) > 0) {
                        msg.ok('删除成功！');
                        grid.reload();
                    } else {
                        MessageOrRedirect(d);
                    }
                });
            }
        } else {
            msg.warning('请选择要删除的行。');
        }
    }
};

//实现动态隐藏列
var cmenu = null;
function createColumnMenu() {
    cmenu = $('<div/>').appendTo('body');
    cmenu.menu({
        onClick: function (item) {
            if (item.iconCls == 'icon-ok') {
                $('#list').datagrid('hideColumn', item.name);
                cmenu.menu('setIcon', {
                    target: item.target,
                    iconCls: 'icon-empty'
                });
            } else {
                $('#list').datagrid('showColumn', item.name);
                cmenu.menu('setIcon', {
                    target: item.target,
                    iconCls: 'icon-ok'
                });
            }
        }
    });
    var fields = $('#list').datagrid('getColumnFields');
    for (var i = 0; i < fields.length; i++) {
        var field = fields[i];
        var col = $('#list').datagrid('getColumnOption', field);
        cmenu.menu('appendItem', {
            text: col.title,
            name: field,
            iconCls: 'icon-ok'
        });
    }
}

//实现动态隐藏列结束

//双击编辑表单焦点消失后保存
var editIndex = undefined;
function endEditing() {
    if (editIndex == undefined) { return true }
    if ($('#list').datagrid('validateRow', editIndex)) {
        $('#list').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function onDblClickCell(index, field) {
    if (editIndex != index) {
        if (endEditing()) {
            $('#list').datagrid('selectRow', index)
            $('#list').datagrid('beginEdit', index);
            var ed = $('#list').datagrid('getEditor', { index: index, field: field });
            if (ed) {
                ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                //这个写法很有意思
                //为了方便 ,类似字段要同事写两个值 1把部门id写入隐藏字段2把标题换成值写入 显示字段

            }
            editIndex = index;
        } else {
            setTimeout(function () {
                $('#list').datagrid('selectRow', editIndex);
            }, 0);
        }
    }
}

function onUnselect(index, row) {
    //alert(index);
}

function onCancelEdit(index, row) {
    //alert(index);
}
function onClickRow(index, row) {
    if (editIndex != undefined) {
        //alert("正在编辑的行是：" + editIndex);
        //alert("验证正在编辑的行：" + $('#list').datagrid('validateRow', editIndex));
        if ($('#list').datagrid('validateRow', editIndex)) {//如果验证正在编辑的行数据有效则
            $("#list").datagrid('endEdit', editIndex);//如果点其他行，结束编辑正在编辑的行
            editIndex = undefined;
        } else {
            msg.warning("还有一行没编辑完啦！！");
        }
    }
    $("#list").datagrid('selectRow', index);


}

function onSelect(index, row) {

}

function onEndEdit(index, row, changes) {
    //alert('结束编辑'+index+JSON.stringify(row));
    var o = {};
    var query = JSON.stringify(row);
    o.jsonEntity = query;
    o.action = 'edit';
    o.keyid = row.KeyId;
    query = "json=" + JSON.stringify(o);
    //alert(query);
    //表格内编辑模式编辑成功不提示信息
    jQuery.ajaxjson(actionURL, query, function (d) {
        //if (parseInt(d) > 0) {
        //    msg.ok('编辑成功！');
        //    hDialog.dialog('close');
        grid.reload();
        // } else {
        //     MessageOrRedirect(d);
        // }
    });

}
function append() {
    if (endEditing()) {
        $('#list').datagrid('appendRow', { status: 'P' });
        editIndex = $('#list').datagrid('getRows').length - 1;
        $('#list').datagrid('selectRow', editIndex)
            .datagrid('beginEdit', editIndex);
    }
}
function removeit() {
    if (editIndex == undefined) { return }
    $('#list').datagrid('cancelEdit', editIndex)
        .datagrid('deleteRow', editIndex);
    editIndex = undefined;
}
function accept() {
    if (endEditing()) {
        $('#list').datagrid('acceptChanges');
    }
}
function reject() {
    $('#list').datagrid('rejectChanges');
    editIndex = undefined;
}
function getChanges() {
    var rows = $('#list').datagrid('getChanges');
    alert(rows.length + ' rows are changed!');
}
//双击编辑表单焦点消失后保存结束

//自定义搜索开始
function mySearch() {
    //page=1&rows=20&filter={"groupOp":"AND","rules":[{"field":"unit","op":"cn","data":"昆明"},{"field":"connman","op":"cn","data":"朱光明"}],"groups":[]}
    var myunit = $("#myUnit").textbox('getValue');
    var connman = $("#myConnMan").textbox('getValue');
    var query = '{"groupOp":"AND","rules":[],"groups":[]}';
    var o = JSON.parse(query);
    var i = 0;
    if (myunit != '' && myunit != undefined) {//假如单位搜索不为空
        o.rules[i] = JSON.parse('{"field":"unit","op":"cn","data":"' + myunit + '"}');
        i = i + 1;
    }
    if (connman != '' & connman != undefined) {//联系人不为空
        o.rules[i] = JSON.parse('{"field":"connman","op":"cn","data":"' + connman + '"}');
    }

    $('#list').datagrid('reload', { filter: JSON.stringify(o) });


}


//自定义搜索结束

//操作列过滤
function formatOper(val, row, index) {
    var s = '';
    //alert(row.KeyId);
    if (row.printsj == 1) {//打印收据
        s = s + '<input type="button" value="打印入住收据" onclick="printx(' + row.KeyId + ',\'printsj\')">';
    }
    if (row.printzfht == 1) {//打印租房合同
        s = s + '<input type="button" value="签租房合同" onclick="printx(' + row.KeyId + ',\'printzfht\')">';
    }
    if (row.printzcht == 1) {//打印租车合同
        s = s + '<input type="button" value="打印电瓶车租赁合同" onclick="printx(' + row.KeyId + ',\'printzcht\')">';
    }
    if (row.printwxts == 1) {//打印温馨提示
        s = s + '<input type="button" value="打印温馨提示" onclick="printx(' + row.KeyId + ',\'printwxts\')">';
    }
    if (row.printyzsc == 1) {//打印业主手册
        s = s + '<input type="button" value="打印业主手册" onclick="printx(' + row.KeyId + ',\'printyzsc\')">';
    }
    //理论上每一个单子都有退的手续
    //if (row.printtfsx == 1) {//打印退房收据
    //type = 'printtfsx';
    //续费办理特别注意  在订单表里是userid 在房间表room  里是userids
    if (row.orderstatus != -1) {//正常的订单才可以显示这两项
        var c = '000000';
        var q = '费用正常';
        if (row.isqian == '' || row.isqian==null) {
            q = '费用正常';
            c = '000000';
        } else {
            q = row.isqian;
            if (q=="欠费") {
                c = 'ff66cc'
            }
            
        }


        s = s + '<input type="button"  style="color:#'+c+';" value="'+q+'" onclick="qianfei(' + row.KeyId + ',\'printtfsx\')">';
        s = s + '<input type="button"  style="color:#ff0000;" value="增减人" onclick="addman(' + row.KeyId + ',\'printtfsx\')">';
        s = s + '<input type="button"  style="color:#;" onclick="OrderPrint(\'' + row.roomno + '续费办理\',\'/mjrooms/roompay.aspx?userids=' + row.usersid + '&roomid=' + row.roomid + '&orderid=' + row.KeyId + '\')" value="续费办理">';
        s = s + '<input type="button"  style="color:#ff0000;" value="退租办理" onclick="printx(' + row.KeyId + ',\'printtfsx\')">';
    }


    var t = row.edNumber;
    //alert(t);
    if (t.indexOf("RZ") > -1) {//
        //调用系统方法
        if (row.orderstatus == 0) {
            console.log("系统提示：入住单、状态为0标识正常");
            if (row.istui == "是") {
                s = s + '<input type="button"  style="color:#ff00ff;" value="取消退房登记" onclick="istuiok(' + row.KeyId + ',' + row.roomid + ',\'\')">';
            } else {
                s = s + '<input type="button"  style="color:#ff0000;" value="退房登记" onclick="istuiok(' + row.KeyId + ',' + row.roomid + ',\'是\')">';
            }

        }
    }

    //}

    return s;


}

function qianfei(keyid) {
    $.ajax({
        type: "POST",
        url: "/mjrooms/ashx/qianfei.ashx?keyid=" + keyid + "",
        data: {},
        dataType: "json",
        beforeSend: function () { },
        complete: function () { },
        success: function (d) {
            //alert("发送结果：" + JSON.stringify(d));
            console.log("欠费处理完毕:keyid" + keyid);
            grid.reload();
        }
    });
}



function addman(keyid) {
    console.log("增减人操作keyid是" + keyid);
    var rows = grid.getSelectedRow();
    if (rows) {
        var hDialog = top.jQuery.hDialog({
            title: '增减入住人', width: 1000, height: 600, href: '/mjorder/html/addman.html', iconCls: 'icon-add',
            toolbar: [{
                text: '加一个',
                iconCls: 'icon-add',
                handler: function () {
                    //alert('edit');
                    var v = top.$("#addman tr").length;
                    var s = "<tr style='display: ;'><td>第"+(v+1)+"个</td><td><li style='margin-top:5px;'>姓名：<input type='text' name='usernames' class='easyui-textbox usernames' value=''>身份证号：<input type='text' name='useridcards' class='easyui-textbox useridcards' value=''>手机号码：<input type='text' name='usermobiles' class='easyui-textbox usermobiles' value=''></li></td></tr>";
                    top.$("#addman").append(s);

                    //绑定样式
                    top.$(".usernames").textbox({//姓名
                        required: true,
                        validType: 'CHS'
                    });
                    top.$(".useridcards").textbox({//身份证号码
                        required: true,
                        validType: 'idcard'
                    });
                    top.$(".usermobiles").textbox({//手机
                        required: true,
                        validType: 'mobile'
                    });

                }
            }, {
                text: '减一个',
                iconCls: 'icon-delete',
                handler: function () {
                    var v = top.$("#addman tr").length;
                    //alert("有："+v);
                    if (v == 1) {//只有一个时不能删除
                        top.$.messager.alert("注意", "至少要有一个入住人！！！");
                        //$.messager.alert('警告', '表单还有信息没有填完整！');
                    } else {
                        top.$("#addman tr:last").remove();
                    }


                    //alert('help');
                }
            }],
            onLoad: function () {

                
                //绑定样式
                top.$(".usernames").textbox({//姓名
                    required: true,
                    validType: 'CHS'
                });
                top.$(".useridcards").textbox({//身份证号码
                    required: true,
                    validType: 'idcard'
                });
                top.$(".usermobiles").textbox({//手机
                    required: true,
                    validType: 'mobile'
                });

                //处理居住人
                if (rows.jzrs > 1) {
                    for (var i = 0; i < rows.jzrs - 1; i++) {
                        //insertjzr();//插入居住人 有几个插入几次-1
                        var v = top.$("#addman tr").length;
                        var s = "<tr style='display: ;'><td>第" + (v + 1) + "个</td><td><li style='margin-top:5px;'>姓名：<input type='text' name='usernames' class='easyui-textbox usernames' value=''>身份证号：<input type='text' name='useridcards' class='easyui-textbox useridcards' value=''>手机号码：<input type='text' name='usermobiles' class='easyui-textbox usermobiles' value=''></li></td></tr>";
                        top.$("#addman").append(s);
                        //绑定样式
                        top.$(".usernames").textbox({//姓名
                            required: true,
                            validType: 'CHS'
                        });
                        top.$(".useridcards").textbox({//身份证号码
                            required: true,
                            validType: 'idcard'
                        });
                        top.$(".usermobiles").textbox({//手机
                            required: true,
                            validType: 'mobile'
                        });
                    }
                    //拆分字符
                    var usernamesarr = new Array(); //定义一数组 
                    usernamesarr = rows.usernames.split(","); //字符分割 
                    var useridcardsarr = new Array();//身份证数组
                    useridcardsarr = rows.useridcards.split(",");
                    var usermobilesarr = new Array();//手机号数组
                    usermobilesarr = rows.usermobiles.split(",");
                    for (i = 0; i < usernamesarr.length; i++) {
                        //document.write(strs[i] + "<br/>"); //分割后的字符输出 
                        top.$(".usernames").eq(i).textbox('setValue', usernamesarr[i]);
                        top.$(".useridcards").eq(i).textbox('setValue', useridcardsarr[i]);
                        top.$(".usermobiles").eq(i).textbox('setValue', usermobilesarr[i]);
                    }
                    console.log("居住人数大于1");
                } else {//如果只有一个，直接处理

                    top.$(".usernames").textbox('setValue', rows.usernames);
                    top.$(".usernames").textbox('readonly', true);
                    top.$(".useridcards").textbox('setValue', rows.useridcards);
                    top.$(".useridcards").textbox('readonly', true);
                    top.$(".usermobiles").textbox('setValue', rows.usermobiles);
                    top.$(".usermobiles").textbox('readonly', true);
                    console.log("居住人数为1");
                }




            },
            submit: function () {
                //alert(top.$("#uiform").form('enableValidation').form('validate'));
                //alert(top.$("#uiform").form('validate'));
                //原来用的是这种方法 alert(top.$('#uiform').validate().form());
                if (top.$("#uiform").form('validate')) {
                    var query = createParam('edit', rows.KeyId);;
                    jQuery.ajaxjson('/mjrooms/ashx/addman.ashx?roomid=' + rows.roomid + '', query, function (d) {
                        if (d.status > 0) {
                            msg.ok('入住人修改成功，系统仅修改了房间表、订单表居住人信息。其他数据并未发生改变！');
                            hDialog.dialog('close');
                            grid.reload();
                        } else {
                            MessageOrRedirect(d);
                        }
                    });
                } else {
                    msg.warning('请填写必填项！');
                }
                //
                return false;
            }
        });
    } else {
        msg.warning('请先选中需要修改的订单。');
    }

}


//操作列过滤


//创建面板
function createFrame(url) {
    var s = '<iframe scrolling="auto" frameborder="0"  style="width:100%;height:100%;" src="' + url + '" ></iframe>';
    return s;
}

function istuiok(kid, roomid, istui) {
    console.log("退房登记ID:" + kid);

    top.$.messager.prompt('提示信息', '请备注信息：', function (r) {
        if (r) {
            $.ajax({
                url: '/mjrooms/ashx/istui.ashx?KeyId=' + kid + '&roomid=' + roomid + '&istuinote=' + r + '&istui=' + istui + '',
                type: 'POST', //GET
                async: true,    //或false,是否异步
                data: {
                    //name:'yang',age:25

                },
                timeout: 5000,    //超时时间
                dataType: 'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                beforeSend: function (xhr) {
                    console.log(xhr)
                    console.log('发送前')
                },
                success: function (data, textStatus, jqXHR) {
                    //alert(data);
                    if (data.status == 1) {
                        //alert(data.msg);
                        top.$.messager.alert('恭喜', data.msg);
                    } else {
                        top.$.messager.alert('注意', data.msg);
                    }
                    $('#list').datagrid('clearSelections').datagrid('reload', { filter: '' });//刷新当前表单
                    console.log(data);
                    console.log(textStatus);
                    console.log(jqXHR);


                },
                error: function (xhr, textStatus) {
                    console.log('错误')
                    console.log(xhr)
                    console.log(textStatus)
                },
                complete: function () {
                    console.log('结束')
                }
            });

        }
    });




}



//打印
function printx(id, type) {
    switch (type) {
        case "printsj"://入住收据
            OrderPrint('打印入住收据', 'mjprint/rzsj.aspx?KeyId=' + id + '');
            break;
        case "printwxts"://温馨提示
            OrderPrint('打印温馨提示', 'mjprint/wxts.aspx');
            break;
        case "printyzsc"://业主手册
            OrderPrint('打印业主手册', 'mjprint/yzsc.aspx');
            break;
        case "printzfht"://租房合同
            OrderPrint('打印租房合同', 'mjprint/zfht.aspx?KeyId=' + id + '');
            break;
        case "printzcht"://租车合同
            OrderPrint('打印租车合同', 'mjprint/zcht.aspx?KeyId=' + id + '');
            break;
        case "printtfsx"://退房手续  //下面是一个关闭并打开的过程
            //var hasTab = top.$('#tabs').tabs('exists', '退房手续');
            //if (!hasTab) {
            //    top.$('#tabs').tabs('add', {
            //        title: '退房手续',
            //        content: createFrame('/MJOrder/overOrder.aspx'),
            //        //closable: (subtitle != onlyOpenTitle),
            //        icon: '/css/icon/32/note.png'
            //    });
            //} else {
            //    top.$('#tabs').tabs('select', '退房手续');
            //    var tab = top.$('#tabs').tabs('getSelected');  // 获取选择的面板
            //    //刷新当前面板
            //    tab.panel('refresh', '/MJOrder/overOrder.aspx');

            //    //closeTab('refresh'); //选择TAB时刷新页面
            //}
            //top.$('#tabs').tabs('close', '入住手续主表');//关闭办理入住手续
            top.addTab('退租办理', 'mjrooms/tuiroom.aspx?KeyId=' + id + '', 'icon-group_edit');
            //原退租手续
            //OrderPrint('打印退房手续', 'mjprint/tfsj.aspx?KeyId=' + id + '');
            break;


        default:
            break;
    }

}

//打印
//配送打印
function OrderPrint(mtitle, murl) {
    //alert(murl);
    var dialog = $.dialog({
        title: mtitle,
        content: 'url:' + murl,
        min: false,
        max: false,
        lock: true,
        width: 850,
        height: 550
    });
}


//单选多选开关
$('#selectSwitch').switchbutton({
    checked: false,
    onChange: function (checked) {
        if (checked) {
            $('#list').datagrid({ singleSelect: false });//多选
        } else {
            $('#list').datagrid({ singleSelect: true });//单选
        }
    }
})

//订单状态筛选
$("#orderstatus").combobox({
    valueField: 'id',
    textField: 'value',
    data: [{
        id: '999',
        value: '全部状态',
    }, {
        id: '0',
        value: '正常'
    }, {
        id: '-1',
        value: '已结算'
    }],
    onSelect: function (rec) {
        //alert(rec.id+"k");
        if (rec.id == 0) {//正常订单
            $('#list').datagrid('reload', { filter: '{"groupOp":"AND","rules":[{"field":"orderstatus","op":"eq","data":"0"}],"groups":[]}' });
        }
        if (rec.id == -1) {
            $('#list').datagrid('reload', { filter: '{"groupOp":"AND","rules":[{"field":"orderstatus","op":"eq","data":"-1"}],"groups":[]}' });
        }
        if (rec.id == 999) {
            $('#list').datagrid('reload', { filter: '' });
        }

    }
});

//订单类型筛选

//订单状态筛选
$("#ordertype").combobox({
    valueField: 'id',
    textField: 'value',
    data: [{
        id: '999',
        value: '全部类型'
    }, {
        id: 'RZ',
        value: '入住'
    }, {
        id: 'XF',
        value: '续费'
    }],
    onSelect: function (rec) {
        //alert(rec.id+"k");
        if (rec.id == 'RZ') {//入住
            $('#list').datagrid('reload', { filter: '{"groupOp":"AND","rules":[{"field":"edNumber","op":"bw","data":"RZ"}],"groups":[]}' });
        }
        if (rec.id == 'XF') {
            $('#list').datagrid('reload', { filter: '{"groupOp":"AND","rules":[{"field":"edNumber","op":"bw","data":"XF"}],"groups":[]}' });
        }
        if (rec.id == '') {
            $('#list').datagrid('reload', { filter: '' });
        }

    }
});






//这里涉及到父子窗口调用问题 父窗口是mjorder.aspx 子窗口是company.aspx
function PrintXF(e) {
    var dialog = $.dialog({
        title: "续费打印",
        content: 'url:' + '/mjprint/xfprint.aspx?edNumber=' + e,
        min: false,
        max: false,
        lock: true,
        width: 850,
        height: 550
    });
    //top.closeTab('refresh');

}

function PrintTZ(e) {
    var dialog = $.dialog({
        title: "退房收据打印",
        content: 'url:' + '/mjprint/tzprint.aspx?edNumber=' + e,
        min: false,
        max: false,
        lock: true,
        width: 850,
        height: 550
    });

}


function reprintxf(e) {
    console.log("打印订单号:" + e);
    alert(e);


}



/* 
* 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时：分钟：秒 
* 其中，年月日为全格式，例如 ： 2010-10-12 01:00:00 
* 返回精度为：秒，分，小时，天
*/

function GetDateDiff(startTime, endTime, diffType) {
    //将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
    startTime = startTime.replace(/\-/g, "/");
    endTime = endTime.replace(/\-/g, "/");

    //将计算间隔类性字符转换为小写
    diffType = diffType.toLowerCase();
    var sTime = new Date(startTime);      //开始时间
    var eTime = new Date(endTime);  //结束时间
    //作为除数的数字
    var divNum = 1;
    switch (diffType) {
        case "second":
            divNum = 1000;
            break;
        case "minute":
            divNum = 1000 * 60;
            break;
        case "hour":
            divNum = 1000 * 3600;
            break;
        case "day":
            divNum = 1000 * 3600 * 24;
            break;
        default:
            break;
    }
    return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
}

//var result = GetDateDiff("2010-02-26 16:00:00", "2011-07-02 21:48:40", "day");
//document.write("简明现代魔法 www.nowamagic.net 建站已有" + result + "天了。");
//alert(result);


//编辑时候
function myedit(edNumber, MJOrderid, userids, roomid) {
    console.log("编辑单号：" + edNumber);
    console.log("订单编号：" + MJOrderid);
    console.log("用户id:" + userids);
    console.log("房间号:" + roomid)
    var t = edNumber;
    //alert(t);

    if (t.indexOf("RZ") > -1) {//
        //调用系统方法
        top.addTab('修改入住收据', '/MJOrderDetail/MJOrderMainEdit.aspx?ednumber=' + edNumber + '&mjorderid=' + MJOrderid + '', 'icon-group_edit');
    }
    if (t.indexOf("XF") > -1) {
        console.log("修改续费收据");
        top.addTab('修改续费收据', '/mjrooms/roompayedit.aspx?edNumber=' + edNumber + '&roomid=' + roomid + '&userids=' + userids + '&orderid=' + MJOrderid + '', 'icon-group_edit');
    }


}



Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//调用： 

//var time1 = new Date().Format("yyyy-MM-dd");
//var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss"); 


function tab(date) {
    var oDate = new Date();
    var nY = oDate.getFullYear();
    var nM = oDate.getMonth();
    var nD = oDate.getDate();
    var newDate = new Date(nY, nM, nD, 0, 0, 0);
    var date = date.split('-');
    var lastDate = new Date(date[0], (date[1] - 1), date[2], 0, 0, 0);
    var result = '';
    if (newDate.getTime() > lastDate.getTime()) {
        //result = date[0] + '年' + date[1] + '月' + date[2] + '过期' + (newDate.getTime() - lastDate.getTime()) / 86400000 + '天';
        result = '<font color=ff0000>过期' + (newDate.getTime() - lastDate.getTime()) / 86400000 + '天</font>';


    } else {
        //result = date[0] + '年' + date[1] + '月' + date[2] + '还有' + Math.abs(newDate.getTime() - lastDate.getTime()) / 86400000 + '天';
        result = '还有' + Math.abs(newDate.getTime() - lastDate.getTime()) / 86400000 + '天';
    }
    return result;
}
console.log(tab('2015-09-20'));
